﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

using SugarWebApi.Json;

namespace SugarWebApi.Processors
{
	public abstract class RestProcessor : SugarWebProcessor
	{

		#region Constructors

		public RestProcessor(
			string url) : base(url)
		{
		}

		#endregion

		#region Properties

		public virtual string RestEndPoint
		{
			get { return string.Empty; }
		}

		#endregion

		#region Methods

		protected virtual object CreateAndProcessRequest(
			object restparameters)
		{
			return ProcessWebRequest(CreateRestRequest(restparameters));
		}

		protected virtual WebRequest CreateRestRequest(
			object restparameters)
		{
			HttpWebRequest request = WebRequest.Create(this.RestEndPoint) as HttpWebRequest;
			request.Method = "POST";
			request.ContentType = "application/json";
			JsonSerializer.Serialize(request.GetRequestStream(), restparameters);

			return request as WebRequest;
		}

		protected virtual object ProcessWebRequest(
			WebRequest request)
		{
			object result = null;
			using (HttpWebResponse response = (request as HttpWebRequest).GetResponse() as HttpWebResponse)
			{
				// for Debugging
				Trace.Debug("REST Responce of {0}, HTTP {1}:{2}", response.ResponseUri, response.StatusCode, response.StatusDescription);
				foreach (string key in response.Headers.AllKeys)
				{
					Trace.Debug("\t{0}:\t{1}", key, response.Headers[key]);	
				}

				// Deserialize
				using (Stream input = response.GetResponseStream())
				{
					result = JsonSerializer.Deserialize(input);
				}
				response.Close();
			}
			return result;
		}


		#endregion
	}
}
